package com.cheer.ba.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;

import com.cheer.ba.R;
import com.cheer.ba.cache.preference.Session;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.model.PushMessageModel;
import com.cheer.ba.model.PushMessageModel1;
import com.cheer.ba.utils.LogUtils;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.utils.SystemUtils;
import com.cheer.ba.utils.ToastUtil;
import com.cheer.ba.view.activity.AddOilCardAty;
import com.cheer.ba.view.activity.CommH5Aty;
import com.cheer.ba.view.activity.LoginAty;
import com.cheer.ba.view.activity.MyOilCardAty;
import com.cheer.ba.view.activity.RegistGiftAty;
import com.example.jpushdemo.Logger;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

import cn.jpush.android.api.CustomPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * <p/>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
    private static final String TAG = "JPush";

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            Bundle bundle = intent.getExtras();
            Logger.d(TAG, "收到后台推送----------------" + intent.getAction());

            if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
                String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
                Logger.d(TAG, "[MyReceiver] 接收Registration Id : " + regId + "----------------------");
                //send the Registration Id to your server...

            } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
                Logger.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: ---------------");
                PushMessageModel model = pushJson(bundle.getString(JPushInterface.EXTRA_MESSAGE));
                LogUtils.LogD(TAG, model.toString());
                if (null != model) {
                    //判断app进程是否存活
                    if (SystemUtils.isAppAlive(context, "com.cheer.ba")) {
                        LogUtils.LogD("注册大礼包", "-------------" + Session.getUserIsLogin() + "--" + model.msgId);
                        if (Session.getUserIsLogin()) {
                            if (TextUtils.equals("1001", model.msgId)) {
                                //支付成功
//                                BaseEvent event = new BaseEvent();
//                                event.type = IntentKey.Login.KEY_NOTICE_PAY;
//                                EventBus.getDefault().post(event);
                                LogUtils.LogD(TAG, "支付成功-----------MyReceiver");
                            } else if (TextUtils.equals("1002", model.msgId)) {
                                //积分变更
                                BaseEvent event = new BaseEvent();
                                event.type = IntentKey.Login.KEY_NOTICE_POINT;
                                EventBus.getDefault().post(event);
                                LogUtils.LogD(TAG, "积分变更-----------MyReceiver");
                            } else if (TextUtils.equals("1005", model.msgId)) {
                                //企业认证通过
                                Session.setUserOrgId(model.data.orgId);
                            } else if (TextUtils.equals("1010", model.msgId)) {
                                //注册大礼包
                                LogUtils.LogD("注册大礼包", "-------------跳转");
                                BaseEvent event = new BaseEvent();
                                event.type = ConstantTag.REGISTER_GIFT;
                                EventBus.getDefault().post(event);
                            }
                        }
                    }
                }
            } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
                Logger.d(TAG, "[MyReceiver] 接收到推送下来的通知---------------");
                int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
                Logger.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId + "---------------");

            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                Logger.d(TAG, "[MyReceiver] 用户点击打开了通知--------");
                String json = pushMsg(bundle.getString(JPushInterface.EXTRA_EXTRA));
                PushMessageModel pushModel = null;
                if (!StringUtils.isEmpty(json)) {
                    pushModel = pushJson(json);
                }
                if (null != pushModel) {
                    LogUtils.LogD(TAG, pushModel.toString());
                    Logger.d(TAG, "model不为空");
                    //判断app进程是否存活
                    if (SystemUtils.isAppAlive(context, "com.cheer.ba")) {
                        Logger.d(TAG, "app进程未关闭");
                        if (pushModel.msgId.equals("1002")) {
                            Logger.d(TAG, "1002拦截");
                            return;
                        }
                        showOtherAty(context, pushModel);
                    } else {
                        Logger.d(TAG, "app进程关闭");
                        Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage("com.cheer.ba");
//                        launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                        launchIntent.putExtra(IntentKey.General.KEY_TYPE, IntentCode.Jpush.JPUSH_CLICK);
                        launchIntent.putExtra(IntentKey.General.KEY_MODEL, pushModel);
                        context.startActivity(launchIntent);
                    }
                } else {
                    Logger.d(TAG, "model为空");
                }
            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
                Logger.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
                //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

            } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
                //链接断开
                boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
//                ToastUtil.showToast("断开了---" + connected);

                Logger.d(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
            } else {
                Logger.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
            }
        } catch (Exception e) {

        }
    }

    /**
     * 展示其他activity
     */
    public void showOtherAty(Context context, PushMessageModel model) {
        //打开自定义的Activity
        Intent i = null;
        if (TextUtils.equals("1001", model.msgId)) {
            //订单支付
            if (Session.getUserIsLogin()) {
                LogUtils.LogD("JPush", "1001---已登录");
                //支付成功
                BaseEvent event = new BaseEvent();
                event.type = IntentKey.Login.KEY_NOTICE_PAY;
                EventBus.getDefault().post(event);

                i = new Intent(context, MyOilCardAty.class);
            } else {
                LogUtils.LogD("JPush", "1001---未登录");
                i = new Intent(context, LoginAty.class);
                i.putExtra(IntentKey.General.KEY_PAGE, IntentCode.General.BACK_ORDER);
            }
        } else if (TextUtils.equals("1002", model.msgId)) {
            LogUtils.LogD("JPush", "1002---积分变更");
            //积分变更
            BaseEvent event = new BaseEvent();
            event.type = IntentKey.Login.KEY_NOTICE_POINT;
            EventBus.getDefault().post(event);
            //积分变更
            return;
        } else if (TextUtils.equals("1003", model.msgId)) {
            //柴油卡审核通过
            if (Session.getUserIsLogin()) {
                LogUtils.LogD("JPush", "1003---柴油卡审核通过");
                i = new Intent(context, AddOilCardAty.class);
                i.putExtra(IntentKey.General.KEY_DATA, model.data.cardNum);
            } else {
                LogUtils.LogD("JPush", "1003---未登录");
                i = new Intent(context, LoginAty.class);
                i.putExtra(IntentKey.General.KEY_PAGE, IntentCode.General.BACK_ADD_CARD);
                i.putExtra(IntentKey.General.KEY_DATA, model.data.cardNum);
            }
        } else if (TextUtils.equals("1004", model.msgId)) {
            LogUtils.LogD("JPush", "1004---活动推送");
            //活动推送
            i = new Intent(context, CommH5Aty.class);
            i.putExtra(IntentKey.General.KEY_URL, model.data.url);
        }
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(i);
    }

    public String pushMsg(String s) {
        String jsonMsg = "";
        try {
            JSONObject json = new JSONObject(s);
            Iterator<String> it = json.keys();

            while (it.hasNext()) {
                String myKey = it.next().toString();
                if (TextUtils.equals("msg", myKey)) {
                    jsonMsg = json.optString(myKey);
                }
            }
        } catch (JSONException e) {
            Logger.e(TAG, "Get message extra JSON error!");
        }
        return jsonMsg;
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    Logger.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next().toString();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    Logger.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    //send msg to MainActivity
    private void processCustomMessage(Context context, PushMessageModel model) {

        CustomPushNotificationBuilder builder = new
                CustomPushNotificationBuilder(context,
                R.layout.customer_notitfication_layout,
                R.id.icon,
                R.id.title,
                R.id.text);
        // 指定定制的 Notification Layout
        // 指定最顶层状态栏小图标
        builder.layoutIconDrawable = R.drawable.ic_invoice_logo;
        // 指定下拉状态栏时显示的通知图标
        builder.statusBarDrawable = R.drawable.ic_invoice_logo;
        builder.notificationFlags = Notification.FLAG_AUTO_CANCEL
                | Notification.FLAG_SHOW_LIGHTS;  //设置为自动消失和呼吸灯闪烁
        builder.notificationDefaults = Notification.DEFAULT_SOUND
                | Notification.DEFAULT_VIBRATE
                | Notification.DEFAULT_LIGHTS;  // 设置为铃声、震动、呼吸灯闪烁都要
        JPushInterface.setPushNotificationBuilder(2, builder);
//        JPushInterface.setDefaultPushNotificationBuilder(builder);
    }

    /**
     * 解析后台发过来的消息体
     *
     * @param str
     * @return
     */
    public PushMessageModel pushJson(String str) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        PushMessageModel model = new Gson().fromJson(str, PushMessageModel.class);
        return model;
    }

    public PushMessageModel1 pushJson1(String str) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        PushMessageModel1 model = new Gson().fromJson(str, PushMessageModel1.class);
        return model;
    }

    //自定义通知
    protected void setSelfNotification(Context context, PushMessageModel model) {
        NotificationManager manager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
        mBuilder.setContentTitle(model.title);
        mBuilder.setContentText(model.context);
        mBuilder.setTicker(model.context);
        mBuilder.setWhen(System.currentTimeMillis());
        mBuilder.setPriority(Notification.PRIORITY_DEFAULT);
        mBuilder.setDefaults(Notification.DEFAULT_ALL);
        mBuilder.setSmallIcon(R.drawable.ic_invoice_logo);

        LogUtils.LogD("JPush", model.msgId + "-=-=-=-=-=");
        if (TextUtils.equals(model.msgId, "1001")) {
            //支付成功
            BaseEvent event = new BaseEvent();
            event.type = IntentKey.Login.KEY_NOTICE_PAY;
            EventBus.getDefault().post(event);

            //订单支付成功
            if (!Session.getUserIsLogin()) {
                Intent login = new Intent(context, LoginAty.class);
                login.putExtra(IntentKey.General.KEY_PAGE, IntentCode.General.BACK_ORDER);
                PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, login, 0);
//                mBuilder.setAutoCancel(true);
                mBuilder.setContentIntent(pendingIntent);
            } else {
                Intent intent = new Intent(context, MyOilCardAty.class);
                PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
                //给我remoteViews上的控件tv_content添加监听事件
//                remoteViews.setOnClickPendingIntent(R.id.title, pendingIntent2);
                mBuilder.setContentIntent(pendingIntent);
            }
        } else if (TextUtils.equals(model.msgId, "1003")) {
            //油卡申请
            if (!Session.getUserIsLogin()) {
                Intent card = new Intent(context, LoginAty.class);
                card.putExtra(IntentKey.General.KEY_PAGE, IntentCode.General.BACK_ADD_CARD);
                card.putExtra(IntentKey.General.KEY_DATA, model.data.cardNum);
                PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, card, 0);
//                mBuilder.setAutoCancel(true);
                mBuilder.setContentIntent(pendingIntent);
            } else {
                Intent intent = new Intent(context, AddOilCardAty.class);
                intent.putExtra(IntentKey.General.KEY_DATA, model.data.cardNum);
                PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
                //给我remoteViews上的控件tv_content添加监听事件
//                remoteViews.setOnClickPendingIntent(R.id.title, pendingIntent2);
                mBuilder.setContentIntent(pendingIntent);
            }
        } else if (TextUtils.equals(model.msgId, "1004")) {
            //活动
            Intent intent = new Intent(context, CommH5Aty.class);
            intent.putExtra(IntentKey.General.KEY_URL, model.data.url);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
            //给我remoteViews上的控件tv_content添加监听事件
//                remoteViews.setOnClickPendingIntent(R.id.title, pendingIntent2);
            mBuilder.setContentIntent(pendingIntent);
        } else if (TextUtils.equals(model.msgId, "1002")) {
            //积分变更
            BaseEvent event = new BaseEvent();
            event.type = IntentKey.Login.KEY_NOTICE_POINT;
            EventBus.getDefault().post(event);
        }
        //积分
        mBuilder.setAutoCancel(true);
        manager.notify(model.builder_id, mBuilder.build());
    }
}
